<template>
  <div>
    <Headline
      :headline1="$t('m.SystemManagement') + '  /  '"
      :headline2="$t('m.OrganizationsAuthorized')"
    />
    <a-card style="width: 100%">
      <a-tree-select
        v-model="value"
        show-search
        style="width: 20%; height: 40px; margin-right: 15px"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
        :placeholder="$t('m.pleaseChoose')"
        allow-clear
        @change="argumentSelect"
        tree-default-expand-all
      >
        <a-tree-select-node
          v-for="item in departmentList"
          :key="item.id"
          :cont="item"
          :value="item.custorgname"
          :title="item.custorgname"
        >
          <a-tree-select-node
            v-for="int in item.children"
            :key="int.id"
            :cont="int"
            :value="int.custorgname"
            :title="int.custorgname"
          >
            <a-tree-select-node
              v-for="ins in int.children"
              :key="ins.id"
              :cont="ins"
              :value="ins.custorgname"
              :title="ins.custorgname"
            />
          </a-tree-select-node>
        </a-tree-select-node>
      </a-tree-select>
      <a-select
        style="margin-right: 15px; width: 100px"
        v-model="orgType"
        @change="handleSelectChange"
      >
        <a-select-option
          v-for="item in dicsclete"
          :key="item.code"
          :value="item.code"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-button
        type="primary"
        @click="add"
        icon="plus"
        style="margin-right: 15px"
        v-if="isTrue('sys:orgauth:add')"
      >
        {{ $t("m.Add") }}
      </a-button>
      <a-button
        type="primary"
        @click="inquire"
        style="background-color: #67c23a; border-color: #67c23a; color: white"
        v-if="isTrue('sys:orgauth:select')"
        icon="zoom-in"
      >
        {{ $t("m.QueryAuthorization") }}
      </a-button>
      <a-table
        size="small"
        style="margin-top: 20px"
        :columns="columns"
        :rowKey="(record, i) => i"
        :data-source="dataA"
        :pagination="false"
        border
      >
        <div slot="handle" slot-scope="text, tags, i">
          <a-button
            type="danger"
            @click="delitem(text, tags, i)"
            icon="delete"
            v-if="isTrue('sys:orgauth:del')"
            >{{ $t("m.Delete") }}</a-button
          >
        </div>
      </a-table>
      <a-pagination
        class="pages"
        show-size-changer
        :default-current="1"
        :total="totals"
        @change="userPages"
        :pageSizeOptions="['5', '10', '30', '40']"
        @showSizeChange="useronShowSizeChange"
      />
    </a-card>
    <a-modal
      :title="$t('m.TheSecondaryAuthorization')"
      :visible="visible"
      :ok-text="$t('m.Ok')"
      :cancel-text="$t('m.Cancel')"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item :label="$t('m.SelectArea')">
          <a-input v-model="areaValue" disabled> </a-input>
        </a-form-item>
        <a-form-item :label="$t('m.Subdomain')">
          <a-checkbox @change="onChange"
            >{{ $t("m.FullAutomaticAuthorization") }}
          </a-checkbox>
        </a-form-item>
      </a-form>
      <a-input-search
        v-model="forminitialA.key"
        :placeholder="$t('m.PleaseEnterYourSearchTerms')"
        style="width: 300px"
        enter-button
        @search="onSearch"
      />
      <a-table
        size="small"
        style="margin-top: 20px"
        :columns="columnsB"
        :rowKey="(record, i) => i"
        :data-source="dataB"
        :pagination="false"
        :row-selection="{
          onChange: onSelectChange,
          type: 'radio',
          selectedRowKeys: selectedRowKeysList,
        }"
        border
      >
      </a-table>
      <a-pagination
        style="margin-top: 20px"
        show-size-changer
        :default-current="1"
        :total="totalA"
        @change="PagesA"
        :pageSizeOptions="['5', '10', '30', '40']"
        @showSizeChange="onShowSizeChangeA"
        class="pages"
      />
    </a-modal>
    <a-modal
      :title="$t('m.AdministratorLevel2AuthorizationQuery')"
      :visible="visibleB"
      @cancel="handleCancelB"
      :footer="null"
    >
      {{ $t("m.SystemUser") }}
      <a-select
        style="width: 120px; margin-right: 15px"
        v-model="forminitialC.userId"
        @change="handleChange"
      >
        <a-select-option
          :value="item.userid"
          v-for="item in dataB"
          :key="item.userid"
        >
          {{ item.nickname }}
        </a-select-option>
      </a-select>
      {{ $t("m.OrgType") }}
      <a-select
        style="width: 80px; margin-right: 15px"
        default-value="1"
        @change="selectChange"
      >
        <a-select-option
          :value="item.code"
          :key="item.code"
          v-for="item in dataTreeList"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-button type="danger" @click="del" icon="delete">{{
        $t("m.Delete")
      }}</a-button>
       <div  v-if="treeData.length <= 0" style="margin-top: 20px">
          <a-empty></a-empty>
       </div>
      <a-tree
        :tree-data="treeData"

        style="margin-top: 20px"
        :defaultExpandAll="true"
        checkable
        @check="oncheck"
        :replaceFields="replaceFields"
      />
    </a-modal>
    <Delete :dalete="dalete" ref="unidelete" @confirm="delIsok" />
    <Delete :dalete="daleteA" ref="unideleteA" @confirm="delIsokA" />
  </div>
</template>

<script>
import Headline from "@/components/Headline";
import SelectTree from "@/components/common/SelectTree";
import Delete from "@/components/Delete";
import {
  getOrgUserList,
  getSysUserList,
  saveOrgUser,
  delOrgUser,
  getUserOrgList,
} from "@/api/systemmanagement";
import { getdiction } from "@/api/dictionaries";
import { getPerages } from "@/api/keraStase";
import { Setperms } from "@/assets/js/setperms";
import { getWidgetDictionaryList } from "@/api/entrance/cloudDoor";

export default {
  name: "OrganAccredit",
  components: { Headline, SelectTree, Delete },

  data() {
    return {
      forminitialG: {
        groupcode: "SYS0000019",
        // insertall: "-1|全部",
        where: "code<> -1 and code <> -100",
      },
      dataTreeList: [],
      lucy: "",
      autoExpandParent: true,
      selectedKeys: [],
      selectedRowKeysList: [],
      columns: [
        { title: this.$t("m.AdministratorName"), dataIndex: "nickname" },
        { title: this.$t("m.privilegedperson"), dataIndex: "creator" },
        { title: this.$t("m.privilegedTime"), dataIndex: "createdate" },
        {
          title: this.$t("m.Operation"),
          scopedSlots: { customRender: "handle" },
        },
      ],
      dalete: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteThisData"),
      },
      daleteA: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteData"),
      },
      dataA: [],
      diction: {
        groupcode: "SYS0000019",
        insertall: "",
        where: "",
        page: 1,
        start: 0,
        limit: 25,
      },
      forminitial: {
        start: 0,
        limit: 10,
        key: "",
        page: 1,
        ymOrgTreeId: "",
        ymOrgTreeCode: "",
      },
      authinital: {
        ymOrgTreeId: 0,
        key: "",
        start: 0,
        page: 1,
        limit: 10,
      },
      totals: 0,
      visible: false,
      areaValue: "",
      columnsB: [
        {
          title: this.$t("m.Code"),
          dataIndex: "usercode",
        },
        {
          title: this.$t("m.Name"),
          dataIndex: "nickname",
        },
      ],
      dataB: [],
      forminitialA: {
        start: 0,
        limit: 10,
        key: "",
        page: 1,
      },
      totalA: 0,
      forminitialB: {
        userIds: "",
        ymOrgTreeId: "",
        ymOrgTreeCode: "",
        infoType: "1",
        isChild: 0,
      },
      visibleB: false,
      treeData: [],
      replaceFields: {
        children: "children",
        title: "custorgname",
        key: "userorgid",
      },
      orgType: "1",
      departmentList: [],
      value: "",
      dicsclete: [],
      ids: "",
      forminitialC: {
        userId: "",
        infoType: 1,
      },
    };
  },
  created() {
    this._getPerages();
    getdiction({ params: this.diction }).then((res) => {
      this.dicsclete = res.data.data;
    });
    this.parms = Setperms(
      this.$route.fullPath,
      JSON.parse(sessionStorage.getItem("menu"))
    );
    getWidgetDictionaryList({ params: this.forminitialG })
      .then((res) => {
        this.dataTreeList = res.data.data;
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    oncheck(checkedKeys, info) {
      console.log(info);
      console.log(checkedKeys);
      this.selectedKeys = checkedKeys;
    },
    isTrue(str) {
      return this.parms.indexOf(str) !== -1;
    },
    handleSelectChange() {
      this._getPerages();
      this.forminitialB.infoType = this.orgType;
    },
    _getPerages() {
      getPerages({ params: { orgType: this.orgType } }).then((res) => {
        console.log(res);
        this.departmentList = res.data;
        this._chexd();
      });
    },
    selectChange(e) {
      console.log(e);
      this.forminitialC.infoType = e;
      this._getUserOrgList();
    },
    del() {
      if (this.selectedKeys.length <= 0)
        return this.$message.warning("请勾选部门");
      this.$refs.unideleteA.visible = true;
    },
    delIsokA() {
      delOrgUser({ ids: this.selectedKeys.join(",") })
        .then((res) => {
          if (res.data.success == true) {
            this.$message.success(res.data.msg);
          }
          if (res.data.success == false) {
            this.$message.warning(res.data.msg);
          }
          this._getUserOrgList();
        })
        .catch((err) => {
          this.$message.error("操作失败");
        });
      this.$refs.unideleteA.visible = false;
    },
    handleChange(e) {
      this.forminitialC.userId = e;
      this._getUserOrgList();
    },
    _getUserOrgList() {
      getUserOrgList({ params: this.forminitialC })
        .then((res) => {
          console.log(res);
          this.treeData = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleCancelB() {
      this.visibleB = false;
      if (this.item !== undefined) {
        this.item.userid = "";
      }
      setTimeout(() => {
        this.treeData = [];
      }, 100);
      this.forminitialC.userId = "";
    },
    inquire() {
      this.visibleB = true;
      this.getuserlist();
    },
    onSearch() {
      this.getuserlist();
    },
    delitem(text, tags, i) {
      console.log(tags);
      this.ids = tags.id;
      this.$refs.unidelete.visible = true;
    },
    delIsok() {
      delOrgUser({ ids: this.ids })
        .then((res) => {
          if (res.data.success == true) {
            this.$message.success(res.data.msg);
            this._getOrgUserList()();
          }
          if (res.data.success == false) {
            this.$message.warning(res.data.msg);
          }
        })
        .catch((err) => {
          // this.$message.error("操作失败");
        });
      this.$refs.unidelete.visible = false;
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log(selectedRowKeys[0])
      this.forminitialB.userIds = selectedRows[0].userid;
      this.selectedRowKeysList = selectedRowKeys;
    },
    onChange(e) {
      console.log(e);
      if (e.target.checked == true) {
        this.forminitialB.isChild = 1;
      }
      if (e.target.checked == false) {
        this.forminitialB.isChild = 0;
      }
    },
    handleOk() {
      if (this.forminitialB.userIds == "")
        return this.$message.warning("请选择系统管理员");
      console.log(this.forminitialB);
      saveOrgUser(this.forminitialB)
        .then((res) => {
          console.log(res);
          if (res.data.success == true) {
            this._getOrgUserList();
            this.$message.success(res.data.msg);
          }
          if (res.data.success == false) {
            this.$message.warning(res.data.msg);
          }
        })
        .catch((err) => {
          this.$message.error("操作失败");
        });
      this.selectedRowKeysList = [];
      this.visible = false;
    },
    handleCancel() {
      this.visible = false;
    },
    onShowSizeChangeA(page, limit) {
      this.forminitialA.page = page;
      this.forminitialA.limit = limit;
      this.getuserlist();
    },
    PagesA(page, pageSize) {
      this.forminitialA.limit = pageSize;
      this.forminitialA.page = page;
      this.forminitialA.start = (page - 1) * pageSize;
      this.getuserlist();
    },
    getuserlist() {
      getSysUserList({ params: this.forminitialA })
        .then((res) => {
          this.dataB = res.data.data;
          this.totalA = res.data.total;
          console.log(res.data.data);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    add() {
      this.visible = true;
      this.areaValue = this.value;
      this.getuserlist();
    },
    argumentSelect(value, label, extra) {
      if (extra.triggerNode) {
        //获取当前选中的对象信息
        const cont = extra.triggerNode.$attrs.cont;
        // let ymOrgTreeId = []
        // ymOrgTreeId.push(cont.id)
        // ymOrgTreeId.push(cont.parentid)
        console.log(cont);
        this.value = cont.custorgname;
        this.authinital.ymOrgTreeId = cont.id;
        // this.forminitialB.ymOrgTreeId = ymOrgTreeId.join(',');
        this.forminitialB.ymOrgTreeCode = cont.ymorgtreecode;
        this._getOrgUserList();
      }
    },
    _getOrgUserList() {
      getOrgUserList({ params: this.authinital }).then((res) => {
        this.totals = res.data.total;
        this.dataA = res.data.data;
      });
    },
    // 默认展示数据
    _chexd() {
      //默认选择第一条数据
      const item = this.departmentList[0];
      // this.formlists.status = item.status;
      this.value = item.custorgname;
      this.authinital.ymOrgTreeId = item.id;
      this.forminitialB.ymOrgTreeId = item.id;
      this.forminitialB.ymOrgTreeCode = item.ymorgtreecode;
      this._getOrgUserList();
    },
    //分页
    useronShowSizeChange(page, limit) {
      this.authinital.page = page;
      this.authinital.limit = limit;
      this.authinital.start = (page - 1) * limit;
      this._getOrgUserList();
    },
    userPages(page, pageSize) {
      this.authinital.page = page;
      this.authinital.limit = pageSize;
      this.authinital.start = (page - 1) * pageSize;
      this._getOrgUserList();
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
